<?php
declare (strict_types = 1);

namespace app\controller;

use app\validate\MenuValidate;
use think\exception\ValidateException;
use think\facade\Validate;
use think\Request;
use app\model\Menu as MenuModel;
use app\model\Auth as AuthModel;

class Menu extends Base
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $result = $this->getMenuTree();
        if($result) {
            $order = array_column($result, 'order');
            array_multisort($order, SORT_DESC, $result);
        }
        return $this->create($result,'请求菜单数据成功');
    }


    /**
     * 显示菜单tree
     * get
     * @return \think\Response
     */
    public function getSelectTree(){
        $tree = $this->getMenuTree();
        $result = [];
        if($tree){
            $result = $this->getSelectMenuTree($tree);
        }
        return $this->create($result,'请求菜单树成功');
    }

    /**
     * 获取菜单树
     */
    private function getMenuTree(){
        $list = MenuModel::order('order', 'desc')->select()->toArray();
        $tree = [];
        if($list){
            //获取有权限的菜单，如果是超级管理员角色拥有全部权限, role_id = 1
            if($this->role_id !==1){
                //拥有权限的菜单id
                $pubilc_menu_id = AuthModel::where('role_id',$this->role_id)->value('smid');
                //没有权限
                if(!$pubilc_menu_id){
                    return $tree;
                }
                //去掉没有权限的菜单
                $pubilc_menu_id_arr = explode(',',$pubilc_menu_id);
                $list = $this->getMenuParentId($list,$pubilc_menu_id_arr);
            }
            //格式化成层级树
            $list = array_column($list, null, 'id');
            foreach ($list as $v) {
                if (isset($list[$v['parent_id']])) {
                    $list[$v['parent_id']]['children'][] = &$list[$v['id']];
                } else {
                    $tree[] = &$list[$v['id']];
                }
            }
        }
        return $tree;
    }
    //获取子菜单的所有父菜单
    private function getMenuParentId(array $list,$ids,&$result=[]){
        foreach ($list as $v){
            if(in_array($v['id'],$ids)){
                $result[] = $v;
                if($v['parent_id']){
                    $this->getMenuParentId($list,[$v['parent_id']],$result);
                }
            }
        }
        return $result;
    }


    /**
     * @param array $tree
     * @param array $result
     * @return array 返回element-ul select下拉菜单树
     */
    private function getSelectMenuTree(array $tree,array &$result= []){
        static $pleft = 0;
        foreach ($tree as $k => $v) {
            $v['pleft'] = $pleft;
            if (isset($v['children'])) {
                $children = $v['children'];
                unset($v['children']);
                $result[] = $v;
                $pleft +=10;
                $this->getSelectMenuTree($children,$result);
                $pleft -=10;
            } else {
                $result[] = $v;
            }
        }
        return $result;
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $param = $request->param();
        try {
            Validate(MenuValidate::class)->check($param);
        }catch (ValidateException $validateException){
            return $this->create([],$validateException->getError(),400);
        }

        $id = MenuModel::create($param)->getData('id');
        if($id){
            return $this->create($id,'添加菜单成功');
        }else{
            return $this->create([],'添加菜单失败',400);
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        if(!Validate::is($id,'number')) return $this->create([],'id参数不合法',400);

        $data = MenuModel::find($id);
        if(empty($data)){
            return  $this->create([],'无数据',204);
        }else{
            return  $this->create($data,'数据请求成功');
        }
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $param = $request->param();
        if(!Validate::is($id,'number')) return $this->create([],'id参数不合法',400);

        try {
            Validate(MenuValidate::class)->check($param);
        }catch (ValidateException $validateException){
            return $this->create([],$validateException->getError(),400);
        }
        $menu_model = MenuModel::find($id);
        if(!$menu_model) return  $this->create([],'修改失败,菜单不存在',400);

        if($menu_model->save($param)){
            return  $this->create($id,'修改成功');
        }else{
            return  $this->create([],'修改失败',400);
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        if(!Validate::is($id,'number')){
            return  $this->create([],'id参数不合法！',400);
        }
        try{
            MenuModel::find($id)->delete();
            return  $this->create([],'删除成功！');
        }catch (\Error $error){
            return  $this->create([],'错误或无数据！',400);
        }
    }
}
